package com.example.babara.memo.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.babara.memo.R;
import com.example.babara.memo.pojo.Memo;
import com.example.babara.memo.utils.DatabaseHelper;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

public class AddMemoActivity extends Activity implements View.OnClickListener{
    private Button setStartTimeButton;
    private TextView startHourText;
    private TextView startMinuteText;
    private EditText remarkEditText;

    private List<String> scopeList = new ArrayList<>();
    private List<String> repeatList = new ArrayList<>();
    private List<String> ringList = new ArrayList<>();
    private List<String> cardList = new ArrayList<>();


    private Spinner scopeSpinner;
    private Spinner repeatSpinner;
    private Spinner ringSpinner;
    private Spinner cardSpinner;

    private ArrayAdapter<String> scopeAdapter;
    private ArrayAdapter<String> repeatAdapter;
    private ArrayAdapter<String> ringAdapter;
    private ArrayAdapter<String> cardAdapter;

    private Button saveButton;
    private Button cancelButton;
    private ImageView backImage;
    private Memo memo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_memo);
        bindView();
        setScopeList();
        setRepeatList();
        setRingList();
        setCardList();

        Memo memoExsist = (Memo)getIntent().getSerializableExtra("memo");
        if(memoExsist != null){setMemoInfo(memoExsist);}

    }

    public void bindView(){

        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int hour = c.get(Calendar.HOUR_OF_DAY);       //获取当前小时
        int min = c.get(Calendar.MINUTE);          //获取当前分钟
        setStartTimeButton = (Button) findViewById(R.id.set_start_time);
        startHourText = (TextView) findViewById(R.id.start_hour_text);
        startMinuteText = (TextView) findViewById(R.id.start_minute_text);
        remarkEditText = (EditText) findViewById(R.id.remark_edit);

        setTimeFormat(hour, min);

        scopeSpinner = (Spinner)findViewById(R.id.scope_spinner);
        repeatSpinner = (Spinner)findViewById(R.id.repeat_spinner);
        ringSpinner = (Spinner)findViewById(R.id.ring_spinner);
        cardSpinner = (Spinner)findViewById(R.id.card_spinner);
        saveButton = (Button)findViewById(R.id.save_button);
        cancelButton = (Button)findViewById(R.id.cancel_button);
        backImage = (ImageView)findViewById(R.id.add_back);
        memo = new Memo();

        setStartTimeButton.setOnClickListener(this);
        saveButton.setOnClickListener(this);
        cancelButton.setOnClickListener(this);
        backImage.setOnClickListener(this);
    }

    public void setRepeatList(){
        repeatList.add("仅一次");
        repeatList.add("每天");
        repeatList.add("每周末");
        repeatList.add("每工作日");
        repeatList.add("自定义");

        repeatAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, repeatList);
        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        repeatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        repeatSpinner.setAdapter(repeatAdapter);
        //第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        repeatSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
               // myTextView.setText("您选择的是："+ adapter.getItem(arg2));
                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
//                myTextView.setText("NONE");
                arg0.setVisibility(View.VISIBLE);
            }
        });
//        /*下拉菜单弹出的内容选项触屏事件处理*/
//        mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
//            public boolean onTouch(View v, MotionEvent event) {
//                // TODO Auto-generated method stub
//                /**
//                 *
//                 */
//                return false;
//            }
//        });
//        /*下拉菜单弹出的内容选项焦点改变事件处理*/
//        mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
//            public void onFocusChange(View v, boolean hasFocus) {
//                // TODO Auto-generated method stub
//
//            }
//        });
    }

    public void setScopeList(){
        scopeList.add("半小时");
        scopeList.add("1小时");
        scopeList.add("2小时");
        scopeList.add("自定义");

        scopeAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, scopeList);
        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        scopeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        scopeSpinner.setAdapter(scopeAdapter);
        //第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        scopeSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
                // myTextView.setText("您选择的是："+ adapter.getItem(arg2));
                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
//                myTextView.setText("NONE");
                arg0.setVisibility(View.VISIBLE);
            }
        });
//        /*下拉菜单弹出的内容选项触屏事件处理*/
//        mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
//            public boolean onTouch(View v, MotionEvent event) {
//                // TODO Auto-generated method stub
//                /**
//                 *
//                 */
//                return false;
//            }
//        });
//        /*下拉菜单弹出的内容选项焦点改变事件处理*/
//        mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
//            public void onFocusChange(View v, boolean hasFocus) {
//                // TODO Auto-generated method stub
//
//            }
//        });
    }

    public void setRingList(){
        ringList.add("Dream It Possible");
        ringList.add("自定义");

        ringAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, ringList);
        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        ringAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        ringSpinner.setAdapter(ringAdapter);
        //第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        ringSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
                // myTextView.setText("您选择的是："+ adapter.getItem(arg2));
                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
//                myTextView.setText("NONE");
                arg0.setVisibility(View.VISIBLE);
            }
        });
//        /*下拉菜单弹出的内容选项触屏事件处理*/
//        mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
//            public boolean onTouch(View v, MotionEvent event) {
//                // TODO Auto-generated method stub
//                /**
//                 *
//                 */
//                return false;
//            }
//        });
//        /*下拉菜单弹出的内容选项焦点改变事件处理*/
//        mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
//            public void onFocusChange(View v, boolean hasFocus) {
//                // TODO Auto-generated method stub
//
//            }
//        });
    }


    public void setCardList(){
        cardList.add("green 1");
        cardList.add("green 2");
        cardList.add("red 1");
        cardList.add("red 2");

        cardAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, cardList);
        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        cardAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        cardSpinner.setAdapter(cardAdapter);
        //第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        cardSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
                // myTextView.setText("您选择的是："+ adapter.getItem(arg2));
                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
//                myTextView.setText("NONE");
                arg0.setVisibility(View.VISIBLE);
            }
        });
//        /*下拉菜单弹出的内容选项触屏事件处理*/
//        mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
//            public boolean onTouch(View v, MotionEvent event) {
//                // TODO Auto-generated method stub
//                /**
//                 *
//                 */
//                return false;
//            }
//        });
//        /*下拉菜单弹出的内容选项焦点改变事件处理*/
//        mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
//            public void onFocusChange(View v, boolean hasFocus) {
//                // TODO Auto-generated method stub
//
//            }
//        });
    }


    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.set_start_time:
                Calendar currentTime = Calendar.getInstance();
                // 弹出一个时间设置的对话框,供用户选择时间
                new TimePickerDialog(AddMemoActivity.this, 0,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view,
                                                  int hourOfDay, int minute) {
                                //设置当前时间
                                Calendar c = Calendar.getInstance();
                                c.setTimeInMillis(System.currentTimeMillis());
                                // 根据用户选择的时间来设置Calendar对象
                                c.set(Calendar.HOUR, hourOfDay);
                                c.set(Calendar.MINUTE, minute);
                                // ②设置AlarmManager在Calendar对应的时间启动Activity
                                        //提示闹钟设置完毕:
                                setTimeFormat(hourOfDay, minute);
                            }
                        }, currentTime.get(Calendar.HOUR_OF_DAY), currentTime
                        .get(Calendar.MINUTE), false).show();
                break;
            case R.id.save_button:
                groupMemo();
                addOneMemo();
                Toast.makeText(AddMemoActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent(AddMemoActivity.this, MainActivity.class);
                startActivity(intent1);
                this.finish();
                break;
            case R.id.cancel_button:
                Toast.makeText(AddMemoActivity.this, "已经取消", Toast.LENGTH_SHORT).show();
                break;
            case R.id.add_back:
                Intent intent2 = new Intent(AddMemoActivity.this, MainActivity.class);
                startActivity(intent2);
                this.finish();
                break;


        }
    }
    private void groupMemo(){
        memo.setRepeat(repeatSpinner.getSelectedItem().toString());
        memo.setCard(cardSpinner.getSelectedItem().toString());
        memo.setRing(ringSpinner.getSelectedItem().toString());
        memo.setScope(scopeSpinner.getSelectedItem().toString());
        memo.setStartHour(Integer.parseInt(startHourText.getText().toString()));
        memo.setStartMin(Integer.parseInt(startMinuteText.getText().toString()));
        memo.setRemark(remarkEditText.getText().toString());
    }

    private void addOneMemo(){
        DatabaseHelper dbHelper = new DatabaseHelper(this, "memo.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("start_hour", memo.getStartHour());
        values.put("start_main", memo.getStartMin());
        values.put("memo_card", memo.getCard());
        values.put("memo_repeat", memo.getRepeat());
        values.put("memo_scope", memo.getScope());
        values.put("memo_ring", memo.getRing());
        values.put("memo_remark", memo.getRemark());
        db.insert("Memo", null , values);
    }

    public void setMemoInfo(Memo memo){
        startHourText.setText(String.valueOf(memo.getStartHour()));
        startMinuteText.setText(String.valueOf(memo.getStartMin()));
        remarkEditText.setText(memo.getRemark());

        int scopePosition = scopeAdapter.getPosition(memo.getScope());
        int repeatPosition = repeatAdapter.getPosition(memo.getRepeat());
        int cardPosition = cardAdapter.getPosition(memo.getCard());
        int ringPosition = ringAdapter.getPosition(memo.getRing());

        scopeSpinner.setSelection(scopePosition);
        repeatSpinner.setSelection(repeatPosition);
        cardSpinner.setSelection(cardPosition);
        ringSpinner.setSelection(ringPosition);
    }

    public void setTimeFormat(int hour, int min){
        String hourStr = String.valueOf(hour);
        String minStr = String.valueOf(min);
        if(hour < 10){
            hourStr = "0" + hourStr;
        }
        if(min < 10){
            minStr = "0" + minStr;
        }
        startHourText.setText(hourStr);
        startMinuteText.setText(minStr);
    }
}
